using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using UniversalAdmin.Api.Models;
using UniversalAdmin.Application.DTOs;
using UniversalAdmin.Application.Services;

namespace UniversalAdmin.Api.Controllers;

[ApiController]
[Route("api/article-categories")]
public class ArticleCategoriesController : ControllerBase
{
  private readonly IArticleCategoryService _service;

  public ArticleCategoriesController(IArticleCategoryService service)
  {
    _service = service;
  }

  [HttpGet]
  [AllowAnonymous]
  public async Task<IActionResult> GetAll()
  {
    var result = await _service.GetAllActiveAsync();
    return Ok(ApiResponse<List<ArticleCategoryDto>>.Success(result));
  }

  [HttpGet("tree")]
  [AllowAnonymous]
  public async Task<IActionResult> GetTree()
  {
    var result = await _service.GetTreeAsync();
    return Ok(ApiResponse<List<ArticleCategoryTreeDto>>.Success(result));
  }

  [HttpGet("{id:int}")]
  [AllowAnonymous]
  public async Task<IActionResult> GetById(int id)
  {
    var result = await _service.GetByIdAsync(id);
    return result == null ? NotFound() : Ok(ApiResponse<ArticleCategoryDto>.Success(result));
  }

  [HttpPost]
  [Authorize(Roles = "Admin,SuperAdmin")]
  public async Task<IActionResult> Create([FromBody] CreateArticleCategoryDto dto)
  {
    var result = await _service.CreateAsync(dto);
    return Ok(ApiResponse<ArticleCategoryDto>.Success(result, "创建成功"));
  }

  [HttpPut("{id:int}")]
  [Authorize(Roles = "Admin,SuperAdmin")]
  public async Task<IActionResult> Update(int id, [FromBody] UpdateArticleCategoryDto dto)
  {
    var result = await _service.UpdateAsync(id, dto);
    return Ok(ApiResponse<ArticleCategoryDto>.Success(result, "更新成功"));
  }

  [HttpDelete("{id:int}")]
  [Authorize(Roles = "Admin,SuperAdmin")]
  public async Task<IActionResult> Delete(int id)
  {
    await _service.DeleteAsync(id);
    return Ok(ApiResponse.Success("删除成功"));
  }
}